#include <drogon/drogon.h>
#include <string>
#include <sstream>

//#define BOOST_STACKTRACE_USE_ADDR2LINE
#include <boost/stacktrace.hpp>
#include <boost/exception/all.hpp>
#include <boost/filesystem.hpp>

#include "json.hpp"
#include "base64.h"
using namespace std;
using namespace drogon;
using namespace nlohmann;
extern string invoke_module(string file, string param="");
int main() {
	try{
		if(!boost::filesystem::exists("config.json")){
			cout<< "config file not found.";
			return -1;
		}

		app().loadConfigFile("config.json");
		app().registerHandler(
			"/caller",
			[](const HttpRequestPtr& req,
				std::function<void(const HttpResponsePtr&)>&& callback) {
					json req_data;
					stringstream ss;
					ss << req->body();
					req_data << ss;

					auto resp = HttpResponse::newHttpResponse();
					string ret = invoke_module(req_data["filename"],req_data["param"]);
					resp->setBody(base64_encode(ret.c_str(),ret.size()));
					callback(resp);
			},{ Post });
		app().run();
	}catch (boost::exception &e) {
		cout << boost::stacktrace::stacktrace() << endl;
        cout << boost::diagnostic_information(e) << endl;
    }
}